package com.tgpms.web.tongfei.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.tgpms.common.MultipartFileToFile;
import com.tgpms.common.Result;
import com.tgpms.web.tongfei.TongfeiController;
import com.tgpms.web.tongfei.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

@Api(value = "DiaryController", tags = "施工监理日志/报表相关接口")
@RestController
@RequestMapping("/tongfei")
public class DiaryController {
    @Value("${tongfei.path}")
    private String host;

    private String addDiary = "/tofly-sxgk/diary";

    private String addDiaryreport = "/tofly-sxgk/diaryreport";

    /**
     * 新增施工监理日志记录
     */
    @ApiOperation(value = "新增施工监理日志记录", notes = "新增施工监理日志记录", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/diary")
    public Result addDiary(@RequestParam(value = "diary") String jsonString, HttpServletRequest request) {
        Diary diary = JSON.parseObject(jsonString, Diary.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
//            if (CollectionUtil.isNotEmpty(diary.getDiaryfileList())) {
//                List<Diaryfile> diaryfileList = diary.getDiaryfileList();
//                for (int i = 0; i < diaryfileList.size(); i++) {
//                    Diaryfile diaryfile = diaryfileList.get(i);// 图片
//                    paramMap.put("diaryfileList[" + i + "].diaryId", diaryfile.getDiaryId());
//                    paramMap.put("diaryfileList[" + i + "].fileLength", diaryfile.getFileLength());
//                    paramMap.put("diaryfileList[" + i + "].fileName", diaryfile.getFileName());
//                    paramMap.put("diaryfileList[" + i + "].fileType", diaryfile.getFileType());
//                    paramMap.put("diaryfileList[" + i + "].path", diaryfile.getPath());
//                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
//                    paramMap.put(diaryfile.getFileName(), image);
//                    images.add(image);
//                }
//            }

            if (!CollectionUtils.isEmpty(files)){
                for (MultipartFile file : files) {
                    File image = MultipartFileToFile.multipartFileToFile(file);
                    paramMap.put(file.getOriginalFilename(), image);
                    images.add(image);
                }
            }

            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(diary, false, true));
            paramMap.remove("diaryfileList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + addDiary)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            return TongfeiController.tongfeiResponseToResult(r);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 修改施工监理日志记录
     */
    @ApiOperation(value = "修改施工监理日志记录", notes = "修改施工监理日志记录", httpMethod = "POST")
    @PostMapping("/tofly-sxgk/updateDiary")
    public Result updateDiary(@RequestParam(value = "diary") String jsonString, HttpServletRequest request) {
        Diary diary = JSON.parseObject(jsonString, Diary.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            // 图片集合
            if (CollectionUtil.isNotEmpty(diary.getDiaryfileList())) {
                List<Diaryfile> diaryfileList = diary.getDiaryfileList();
                for (int i = 0; i < diaryfileList.size(); i++) {
                    Diaryfile diaryfile = diaryfileList.get(i);// 图片
                    paramMap.put("diaryfileList[" + i + "].diaryId", diaryfile.getDiaryId());
                    paramMap.put("diaryfileList[" + i + "].fileLength", diaryfile.getFileLength());
                    paramMap.put("diaryfileList[" + i + "].fileName", diaryfile.getFileName());
                    paramMap.put("diaryfileList[" + i + "].fileType", diaryfile.getFileType());
                    paramMap.put("diaryfileList[" + i + "].path", diaryfile.getPath());
                    File image = MultipartFileToFile.multipartFileToFile(files.get(i));
                    paramMap.put(diaryfile.getFileName(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(diary, false, true));
            paramMap.remove("diaryfileList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.put(host + addDiary)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            return TongfeiController.tongfeiResponseToResult(r);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 查询当前用户提交的日志信息
     */
    @ApiOperation(value = "查询当前用户提交的日志信息", notes = "查询当前用户提交的日志信息", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/diary/getUserLog")
    public Result getUserLog(@RequestParam("pageNo") Integer current,@RequestParam("size") Integer size, HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("current", current);
        paramMap.put("size", size);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/diary/getUserLog", paramMap, request);
    }

    /**
     * 新增施工监理报表
     */
    @ApiOperation(value = "新增施工监理报表", notes = "新增施工监理报表", httpMethod = "POST")
    @PostMapping(value = "/tofly-sxgk/diaryreport",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result addDiaryreport(@RequestParam(value = "diaryreport") String jsonString, HttpServletRequest request) {
        Diaryreport diaryreport = JSON.parseObject(jsonString, Diaryreport.class);
        List<MultipartFile> files = new ArrayList<>();
        // 获取文件集合
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        if (CollectionUtil.isNotEmpty(fileMap)) {
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 获取单个文件
                MultipartFile mf = entity.getValue();
                files.add(mf);
            }
        }

        // 临时文件,最后要删除
        List<File> images = new ArrayList<>();
        try {
            // 发送给同飞的参数
            Map<String, Object> paramMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(files)){
                for (MultipartFile file : files) {
                    File image = MultipartFileToFile.multipartFileToFile(file);
                    paramMap.put(file.getOriginalFilename(), image);
                    images.add(image);
                }
            }
            // 调用同飞修改接口
            paramMap.putAll(BeanUtil.beanToMap(diaryreport, false, true));
            paramMap.remove("diaryreportfileList");
            paramMap.remove("createTime");
            String token = request.getHeader("tfToken");
            String body = HttpRequest.post(host + addDiaryreport)
                    .header(Header.AUTHORIZATION, "Bearer " + token)
                    .header(Header.CONTENT_TYPE, "multipart/form-data")
                    .form(paramMap)
                    .execute().body();
            R r = JSON.parseObject(body, R.class);
            return TongfeiController.tongfeiResponseToResult(r);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR(e.getMessage());
        } finally {
            MultipartFileToFile.delteTempFile(images);
        }
    }

    /**
     * 分页查询施工监理报表接口
     */
    @ApiOperation(value = "分页查询施工监理报表接口", notes = "分页查询施工监理报表接口", httpMethod = "GET")
    @GetMapping("/tofly-sxgk/diaryreport/page")
    private Result page(Diaryreport diaryreport, HttpServletRequest request){
        Map<String, Object> paramMap = BeanUtil.beanToMap(diaryreport, false, true);
        paramMap.put("orders[0].column", "create_time");
        paramMap.put("orders[0].asc", false);
        return TongfeiController.normalGet("/tofly-sxgk/diaryreport/page", paramMap, request);
    }


}
